import 'dart:io';

import 'package:demo/constants/event_bus_key.dart';
import 'package:demo/model/bean/event/page_destroy_bean.dart';
import 'package:demo/utils/disk_lru_cache.dart';
import 'package:demo/utils/event_bus.dart';
import 'package:demo/utils/native/connectivity.dart';
import 'package:demo/utils/native/crash_analysis.dart';
import 'package:demo/utils/native/package_info.dart';
import 'package:demo/utils/native/path_provider.dart';

/// 插件注册类
class PluginRegistrant {
  /// 插件初始化的状态
  bool _isRegisterNativePlugin = false;
  bool _isRegisterDartPlugin = false;

  /// 工厂模式
  factory PluginRegistrant() => _getInstance();

  /// 单例
  static PluginRegistrant get instance => _getInstance();
  static PluginRegistrant? _instance;

  PluginRegistrant._internal();

  static PluginRegistrant _getInstance() => _instance ??= PluginRegistrant._internal();

  /// 注册原生插件
  void registerNativePlugins() {
    if (_isRegisterNativePlugin) return;
    CrashAnalysisUtils.instance.initBugly();
  }

  /// 注册dart插件
  /// 注入flutter依赖(非原生，原生需要在隐私同意后才可以初始化)
  void registerDartPlugins() async {
    if (_isRegisterDartPlugin) return;

    /// 注册全局eventBus事件
    final EventBus eventBusInstance = EventBus.instance;
    eventBusInstance.monitoring<PageDestroyBean>(EVENT_BUS_PAGE_DESTROY_KEY);

    /// 初始化对应的磁盘缓存，以app临时缓存路径+包名作为文件路径
    final List<dynamic> waitList = await Future.wait([
      PathProviderUtils().tempDirectory,
      PackageInfoUtils().getPackageInfo,
    ]);
    DiskLruCacheUtils.instance.open(
      Directory("${waitList[0].path}/${waitList[1].packageName}"),
      maxSize: 64 * 1024 * 1024,
    );
  }

  /// 释放所有插件
  void releaseAllPlugins() async {
    /// 关闭磁盘缓存
    DiskLruCacheUtils.instance.close();

    /// 清除监听的网络变化
    ConnectivityUtils.instance.destroy();

    /// 清楚bugly监听更新
    CrashAnalysisUtils.instance.destroy();

    /// 清除event bus
    EventBus.instance.destroy();
  }
}
